import os
import json
import time
import asyncio
from ..base import base

from flask import Flask, request, Response
from ..routes.analysis.PlayWrightMcpClient import Client



@base.route('/smart/playbrowser/sse')
def playbrowser_sse():
    task = request.args.get('task')  # 将request访问移到装饰函数内
    
    def event_stream():
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        try:
            client = Client()
            tools = loop.run_until_complete(client.connect_server())
            if not task:  # 使用外部获取的task变量
                yield "data: " + json.dumps({'error': '任务不能为空'}) + "\n\n"
                return
                
            # 调用 PlayWrightMcpClient.py代码中的 chat_loop方法
            yield "data: " + json.dumps({
                'progress': 10,
                'message': '开始处理任务...'
            }) + "\n\n"
            
            response = loop.run_until_complete(client.chat(task))
            exec_cmd_str = loop.run_until_complete(client.get_call_tool(response,tools))
            yield "data: " + json.dumps({
                'progress': 30,
                'message': f"正在执行工具调用...{exec_cmd_str}"
            }) + "\n\n"

            result = loop.run_until_complete(client.execute_tool(response))
            while result != response:
                response = loop.run_until_complete(client.chat(result, "system"))
                exec_cmd_str = loop.run_until_complete(client.get_call_tool(response, tools))
                if exec_cmd_str:
                    yield "data: " + json.dumps({
                        'progress': 50,
                        'message': f"正在执行工具调用...{exec_cmd_str}"
                    }) + "\n\n"
                    result = loop.run_until_complete(client.execute_tool(response))
                else:
                    result = response

            yield "data: " + json.dumps({
                'progress': 100,
                'message': '任务执行完成',
                'result': result
            }) + "\n\n"
            
            # 添加10秒休眠
            time.sleep(10)
        except Exception as e:
            yield "data: " + json.dumps({'error': str(e)}) + "\n\n"
        finally:
            if client and hasattr(client, '_exit_stack'):
                try:
                    loop.run_until_complete(client._exit_stack.aclose())
                except RuntimeError:
                    # Ignore cancel scope errors during cleanup
                    pass
            loop.close()
    
    return Response(event_stream(), mimetype="text/event-stream")
